package com.yonyou.pmclouds.businessobject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.print.client.business.PrintServer;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 云打印服务类
 * @author zhangzhonghao
 */
@Slf4j
@Component
public class PrintService {

    private static final String SAVE_BO_API = "/rest/bomanage/saveBo";

    private static final String QUERY_BO_API = "/rest/bomanage/querybycode";

    private static final String UPDATE_BO_API = "/rest/bomanage/updatebo";

    private static final String QUERY_TEMPLATE_BY_TENANT_API = "/rest/printTemplate/queryBytatent";

    private static final String DELETE_TEMPLATE_API = "/rest/printTemplate/deleteprint";

    private static final String QUERY_BO_BY_TENANT_API = "/rest/bomanage/querybytenant";

    private static final String DELETE_BO_API = "/rest/bomanage/deleteBo";

    private static final String INIT_BUSINESS_API = "/rest/print/initTenantBizz";

    /**
     * 保存业务对象到云打印
     * @param boCode 业务对象编码
     * @param boStr 业务对象结构数据
     * @param tenantId 租户ID
     * @return 保存结果
     */
    public static String saveBoToCloud(String boCode, String boStr, String tenantId) throws BusinessException {
        Map<String, String> params = new HashMap<>();
        params.put("bo_code", boCode);
        params.put("boStr", boStr);
        String result = InvokePostCloudMethod(params, tenantId, SAVE_BO_API);
        log.debug("保存业务对象：" + boCode + ", 返回结果：" + result);
        return result;
    }

    public static String updateBoToCloud(String boCode, String boStr, String tenantId) throws BusinessException {
        String pkBo = getPkBoByCode(boCode, tenantId);
        if(StringUtils.isEmpty(pkBo)){
            return null;
        }
        Map<String, String> params = new HashMap<>();
        params.put("pk_bo", pkBo);
        params.put("boStr", boStr);
        //更新业务对象 bo
        String result = InvokePostCloudMethod(params, tenantId, UPDATE_BO_API);
        log.debug("更新业务对象：" + boCode + ", 返回结果：" + result);
        return result;
    }

    private static String getPkBoByCode(String boCode, String tenantId) throws BusinessException {
        String ret = getBoFromCloud(boCode, tenantId);
        Map retMap = JSON.parseObject(ret, Map.class);
        if(retMap == null){
            return null;
        }
        return (String) retMap.get("BOKey");
    }

    private static String getBoFromCloud(String boCode, String tenantId) throws BusinessException {
        Map<String, String> params = new HashMap<>();
        params.put("bo_code", boCode);
        //查询业务对象 bo
        String result = InvokeGetCloudMethod(params, tenantId, QUERY_BO_API);
        log.debug("查询业务对象：" + boCode + ", 返回结果：" + result);
        return result;
    }

    public static String getPrintCode(String boCode, String tenantId) throws BusinessException {
        String printCode = "";
        String pkBo = getPkBoByCode(boCode, tenantId);
        if(StringUtils.isEmpty(pkBo)){
            return null;
        }
        Map<String, String> params = new HashMap<>();

//        params.put("pk_bo", pkBo);
//        String result = PrintServer.execGet("/rest/printTemplate/gettempbybo", params, tenantId, "");
//        Map<String, JSONArray> jsonMap = JSON.parseObject(result, Map.class);
//        JSONArray jsonArray = jsonMap.get("tempresult");
//        替换上面调用接口为查询该租户下面所有模版，然后过滤，因为上面接口返回修改时间为空，等云打印那边修改后再替换回来

        params.put("tetantId", tenantId);
        // 注意这个key和上面key不同.....
        params.put("tenantId", tenantId);
        String result = InvokePostCloudMethod(params, tenantId, QUERY_TEMPLATE_BY_TENANT_API);
        ArrayList<JSONObject> jsonObjects = JSON.parseObject(result, ArrayList.class);
        if (!jsonObjects.isEmpty()) {
            //暂时只支持一个业务对象对应一个模版
            long maxTime = 0;
            for (JSONObject jsonObject : jsonObjects) {
                if (pkBo.equalsIgnoreCase(jsonObject.getString("pk_bo"))) {
                    JSONObject timeJsonObject = (JSONObject) jsonObject.get("modifiedtime");
                    long time = (long) timeJsonObject.get("time");
                    if (time > maxTime) {
                        maxTime = time;
                        printCode = jsonObject.getString("templatecode");
                    }
                }
            }
        }
        return printCode;
    }

    public static ArrayList<JSONObject> getTemplateByTenantId(String tenantId) throws BusinessException {
        Map<String, String> params = new HashMap<>();
        params.put("tetantId", tenantId);
        params.put("tenantId", tenantId);
        String result = InvokePostCloudMethod(params, tenantId, QUERY_TEMPLATE_BY_TENANT_API);
        return JSON.parseObject(result, ArrayList.class);
    }

    public static String deleteTemplate(String pkTemplate, String tenantId) {
        Map<String, String> params = new HashMap<>();
        params.put("pk_template", pkTemplate);
        return PrintServer.execPost(DELETE_TEMPLATE_API, params, tenantId, "");
    }

    public static ArrayList<JSONObject> getBoByTenantId(String tenantId) throws BusinessException {
        Map<String, String> params = new HashMap<>();
        params.put("tenantId", tenantId);
        String result = InvokeGetCloudMethod(params, tenantId, QUERY_BO_BY_TENANT_API);
        return JSON.parseObject(result, ArrayList.class);
    }

    public static String deleteBo(String pkBo, String tenantId) throws BusinessException {
        Map<String, String> params = new HashMap<>();
        params.put("pk_bo", pkBo);
        return InvokePostCloudMethod(params, tenantId, DELETE_BO_API);
    }

    public static String initTenantFromCloud(String tenantId) throws BusinessException {
        Map<String, String> params = new HashMap<>();
        params.put("tenantId", tenantId);
        return InvokePostCloudMethod(params, tenantId, INIT_BUSINESS_API);
    }

    private static String InvokePostCloudMethod(Map<String, String> params, String tenantId, String invokeMethod) throws BusinessException{
        return PrintServer.execPost(invokeMethod, params, tenantId, "");
    }

    private static String InvokeGetCloudMethod(Map<String, String> params, String tenantId, String invokeMethod) throws BusinessException{
        return PrintServer.execGet(invokeMethod, params, tenantId, "");
    }




}
